<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <table border="1">
        <thead>
            <tr>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>jack</td>
                <td>22</td>
                <td>girl</td>
            </tr>
            <tr>
                <td>lucy</td>
                <td>21</td>
                <td>girl</td>
            </tr>
            <tr>
                <td>tom</td>
                <td>22</td>
                <td>boy</td>
            </tr>
        </tbody>
    </table>
    <script>
        let editing = false;
        let td = null;
        let tdOldText = '';
        document.onclick = function (e) {
            const target = e.target;
            const confirm = target.dataset.confirm;
            const cancel = target.dataset.cancel;
            if (target.nodeName === 'TD' && editing === false) {
                // 1. 将 editing 设置为true 表示当前已经有单元格被编辑，保证每次只有一个单元格被编辑
                editing = true;
                // 2. 保存必要的数据
                td = target;
                tdOldText = target.textContent;

                // 3. 创建可编辑标签对TD内容替换
                target.innerHTML = `<div>
                    <input id="inputEL" type="text" value="${target.textContent}" />
                    <div>
                        <button data-confirm>确定</button> 
                        <button data-cancel>取消</button>
                    </div> 
                </div>`;

            }

            if (confirm !== undefined) {
                // 将输入框中的内容替换给TD
                td.innerHTML = document.getElementById('inputEL').value;
                editing = false;
            }

            if (cancel !== undefined) {
                // 将原来内容替换给TD
                td.innerHTML = tdOldText;
                editing = false;
            }
        }




    </script>
</body>

</html>